package cn.wn.shiro;

import cn.wn.pojo.Permission;
import cn.wn.pojo.User;
import cn.wn.service.PermissionService;
import cn.wn.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;

    /**
     * 认证方法
     * UnknownAccountException  账号错误
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取用户输入的用户名
        String name = (String) token.getPrincipal();
        // 根据用户名查询数据库
        User user = userService.findByName(name);
        // 判断
        if (user == null) {
            return null; // 报错：UnknownAccountException
        }
        // 返回认证信息
        // 参数1：身份对象，通过subject.getPrincipal()获取
        // 参数2：数据库中正确的密码
        // 参数3：加盐。把用户名作为盐。
        // 参数4：realm名称。getName()获取默认名称
        //密码校验：用户输入的用户密码，已经通过token封装； 告诉shiro数据库中正确的密码； shiro自动帮助我们校验
        SimpleAuthenticationInfo sai =
                new SimpleAuthenticationInfo(
                        user,
                        user.getPassword(),
                        ByteSource.Util.bytes(user.getName()),
                        getName()
                );
        return sai;
    }
    /**
     * 授权方法：查询用户的权限并返回给shiro
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //1. 先获取认证后的用户对象
        User user = (User) principals.getPrimaryPrincipal();
        //2. 根据用户id查询权限
        List<Permission> permissions =
                permissionService.findPermissionByUserId(user.getId());

        SimpleAuthorizationInfo sai = new SimpleAuthorizationInfo();
        //3. 遍历用户的权限，返回给shiro
        if (permissions != null && permissions.size() > 0) {
            permissions.forEach(p -> {
                // 添加用户的权限编码
                sai.addStringPermission(p.getPcode());
            });
        }

        return sai;
    }


//    public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
//        super.clearCachedAuthorizationInfo(principals);
//    }
}
